<route lang="json">
{
    "name": "noticeCategoryManage",
    "meta": {
        "title": "控制台-通知分类管理",
        "requiresAuth": true
    }
}
</route>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { createNoticeCategory, deleteNoticeCategory, getNoticeCategoryList, updateNoticeCategory } from '~/api/notice-category'
import { formatDate } from '~/utils/tools'

// 定义通知分类接口类型
interface NoticeCategory {
  _id: string
  categoryId: string
  name: string
  flag: boolean
  createTime?: string
  updateTime?: string
  [key: string]: any
}

// 通知分类列表数据
const categoryList = ref<NoticeCategory[]>([])
const loading = ref(false)

// 表格分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 搜索条件
const searchForm = reactive({
  name: '',
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('添加通知分类')
const formLoading = ref(false)

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  description: '',
  sort: 0,
  flag: true, // 添加状态属性，默认为启用
})

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
}

const formRef = ref()

// 获取通知分类列表
async function fetchCategoryList() {
  loading.value = true
  try {
    const res = await getNoticeCategoryList()
    // 直接使用返回的数据，因为API已经返回了正确的格式
    if (res && Array.isArray(res)) {
      categoryList.value = res
      pagination.total = res.length
    }
    else if (res && typeof res === 'object' && Array.isArray(res.list)) {
      categoryList.value = res.list
      pagination.total = res.total || res.list.length
    }
    else if (res && typeof res === 'object' && Array.isArray(res.data)) {
      categoryList.value = res.data
      pagination.total = res.data.length
    }
    else {
      categoryList.value = []
      pagination.total = 0
    }
  }
  catch (error) {
    console.error('获取通知分类列表失败:', error)
    ElMessage.error('获取通知分类列表失败')
    categoryList.value = []
    pagination.total = 0
  }
  finally {
    loading.value = false
  }
}

// 处理分页变化
function handleCurrentChange(val: number) {
  pagination.currentPage = val
}

function handleSizeChange(val: number) {
  pagination.pageSize = val
  pagination.currentPage = 1
}

// 搜索
function handleSearch() {
  pagination.currentPage = 1
}

// 重置搜索
function resetSearch() {
  searchForm.name = ''
  pagination.currentPage = 1
}

// 过滤数据
const filteredData = computed(() => {
  let result = [...categoryList.value]

  // 按名称筛选
  if (searchForm.name) {
    result = result.filter(item => item.name.includes(searchForm.name))
  }

  return result
})

// 计算当前页的数据
const currentPageData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.value.slice(start, end)
})

// 打开添加对话框
function openAddDialog() {
  dialogTitle.value = '添加通知分类'
  Object.assign(formData, {
    id: '',
    name: '',
    description: '',
    sort: 0,
  })
  dialogVisible.value = true
}

// 打开编辑对话框
function openEditDialog(row: NoticeCategory) {
  dialogTitle.value = '编辑通知分类'
  Object.assign(formData, {
    id: row._id,
    name: row.name,
    description: '',
    sort: 0,
  })
  dialogVisible.value = true
}

// 提交表单
async function submitForm() {
  if (!formRef.value)
    return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid)
      return

    formLoading.value = true
    try {
      const categoryData = {
        name: formData.name,
        description: formData.description,
        sort: formData.sort,
      }

      if (formData.id) {
        // 编辑
        await updateNoticeCategory(formData.id, categoryData)
        ElMessage.success('更新通知分类成功')
      }
      else {
        // 添加
        await createNoticeCategory(categoryData)
        ElMessage.success('添加通知分类成功')
      }
      dialogVisible.value = false
      fetchCategoryList()
    }
    catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
    finally {
      formLoading.value = false
    }
  })
}

// 删除通知分类
function handleDelete(row: NoticeCategory) {
  ElMessageBox.confirm('确定要删除该通知分类吗？相关通知也可能会受到影响！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteNoticeCategory(row._id)
      ElMessage.success('删除成功')
      fetchCategoryList()
    }
    catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 页面加载时获取通知分类列表
onMounted(() => {
  fetchCategoryList()
})
</script>

<template>
  <div class="category-manage-container">
    <div class="category-header">
      <h2 class="category-title">
        通知分类管理
      </h2>
      <el-button type="primary" @click="openAddDialog">
        添加分类
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <div class="form-items">
          <el-form-item label="分类名称">
            <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable style="width: 220px;" />
          </el-form-item>
        </div>
        <div class="form-buttons">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              搜索
            </el-button>
            <el-button @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>

    <!-- 通知分类列表 -->
    <el-card shadow="hover" class="category-card">
      <el-table v-loading="loading" :data="currentPageData" stripe border style="width: 100%">
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" />

        <!-- 名称列 -->
        <el-table-column prop="name" label="分类名称" min-width="150" />

        <!-- 分类ID列 -->
        <el-table-column prop="categoryId" label="分类ID" min-width="150" show-overflow-tooltip />

        <!-- 状态列 -->
        <el-table-column prop="flag" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.flag ? 'success' : 'danger'">
              {{ scope.row.flag ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>

        <!-- 更新时间列 -->
        <el-table-column prop="updateTime" label="更新时间" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="openEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="filteredData.length"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="formData.flag" :active-value="true" :inactive-value="false" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="formLoading" @click="submitForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.category-manage-container {
  padding: 20px;

  .category-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .category-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;

    .search-form {
      display: flex;
      justify-content: space-between;
      width: 100%;

      .form-items {
        display: flex;
        flex-wrap: wrap;
      }

      .form-buttons {
        display: flex;
        align-items: flex-start;
      }
    }
  }

  .category-card {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
